import { useModel } from '@@/plugin-model';
import { AlertComponent, render as renderAmis, ToastComponent } from 'amis';
import { Modal } from 'antd';
import '../scss/sql-edit-form.scss';

const SqlEditForm = (props: any) => {
  const { fetcher, notify, alert, copy } = useModel('amisEnv');

  let amisJSON = {
    type: 'form',
    onFinished: () => {
      props.handleSqlEditFormOpen(false);
      props.ok();
      return true; // 这样可以禁掉 amis 后续的默认行为
    },
    initApi: {
      method: 'get',
      url: '/pageSqlColumn/list',
      data: {
        sqlConfigId: props.values.id,
      },
      responseData: {
        columnList: '${items}',
      },
    },
    api: {
      method: 'put',
      url: '/pageSqlConfig/editSql',
      data: {
        ...props.values,
        sqlContent: '${sqlContent}',
        columnList: '${columnList}',
      },
    },
    data: {
      ...props.values,
    },
    labelWidth: 0,
    body: [
      {
        type: 'editor',
        language: 'sql',
        name: 'sqlContent',
        allowFullscreen: true,
        required: true,
        label: '',
        placeholder: '请在此编写你的SQL语句',
      },
      {
        type: 'input-table',
        name: 'columnList',
        value: '${columnList}',
        addable: true,
        removable: true,
        needConfirm: false,
        columns: [
          {
            label: 'sqlConfigId',
            name: 'sqlConfigId',
            type: 'input-text',
            value: props.values.id,
            visible: false,
            required: true,
          },
          {
            label: '字段',
            name: 'columnName',
            type: 'input-text',
            required: true,
          },
          {
            label: '文字描述',
            name: 'description',
            type: 'input-text',
          },
          {
            label: '字段类型',
            name: 'type',
            type: 'select',
            required: true,
            options: [
              'Integer',
              'BigDecimal',
              'Short',
              'Long',
              'Float',
              'Double',
              'Date',
              'String',
            ],
          },
        ],
      },
    ],
  };

  const handleCancel = () => {
    props.handleSqlEditFormOpen(false);
  };

  return (
    <>
      <Modal
        title={props.editType === 'add' ? '新增组件脚本' : '编辑SQL'}
        destroyOnClose={true}
        maskClosable={false}
        style={{ top: 20 }}
        width={1280}
        open={props.sqlEditFormOpen}
        footer={null}
        closable={true}
        onCancel={handleCancel}
      >
        <ToastComponent key="toast" />
        <AlertComponent key="alert" />
        {renderAmis(
          amisJSON,
          {},
          {
            fetcher: fetcher,
            notify: notify,
            alert: alert,
            copy: copy,
          },
        )}
      </Modal>
    </>
  );
};

export default SqlEditForm;
